<template>
  <template v-if="!proxy.isMobile">
    <div id="nav-menu" class="nav-menu" :class="{ mouseHover }" :style="navStyle">
      <div class="container f f-ac f-sb">
        <img :src="navLogo" id="logo" class="nav-logo" />
        <div class="nav-list f f-1 ml160">
          <div v-for="(item, index) in menuList" :key="item.name" class="nav-item f f-ac f-jc"
            :class="{ active: currentIndex === index }" @click="changeNav(item, index)"
            @mouseenter.stop="mouseenter(item, index)">
            {{ item.name }}
          </div>
          <div v-if="currentIndex !== -1" class="tab-line" :style="{
              left: `calc(33px + ${currentIndex * 120}px)`,
            }" />
        </div>
      </div>
      <div v-if="navChildren.length" class="nav-children" @mouseleave="mouseleave">
        <div class="container g g4 pt28 pb28 gap28-row gap50-col">
          <!-- v-if="hoverIndex != 3" -->
          <div v-for="(item, index) in navChildren" :key="'nc_' + index" class="children-item"
            @click="changePath(item)">
            <div class="item-icon">
              <img v-if="item.icon" :src="item.icon" />
            </div>
            <div class="item-info line-1">
              {{ item.name }}
              <div v-if="item.hot" class="item-hot">HOT</div>
            </div>
            <div class="item-desc line-1">{{ item.desc }}</div>
          </div>
        </div>
        <!-- 级联选择器开始 -->
        <!-- <div class="container" style="display: flex;justify-content: space-between;padding: 20px;"
          v-if="hoverIndex == 3" @click="changePath(navChildren[hoverIndex])">
          <div class="left">
            <el-cascader-panel :options="navChildren" :props="{ expandTrigger: 'hover' }"
              color="#000"></el-cascader-panel>
          </div>
          <div class="right">123</div>
        </div> -->
        <!-- 级联选择器结尾 -->
      </div>

    </div>
  </template>
  <template v-if="proxy.isMobile">
    <div class="nav-menu-mobile" :style="navStyle">
      <img :src="navLogo" class="logo" />
      <van-icon name="wap-nav" :style="iconStyle" @click="expandMenu" />
    </div>
    <van-popup v-model:show="isExpand" closeable close-on-popstate safe-area-inset-bottom position="right"
      class="nav-van-popup">
      <div class="nav-popup">
        <img :src="weblogo1" class="drawer-logo" />
        <div class="nav-popup-list">
          <template v-for="(item, index) in menuList" :key="index">
            <div v-if="item.children && item.children.length" class="nav-popup-group">
              <div class="nav-popup-label" :class="{ active: judgePath(item) }" @click="handleExpandSubNav(item)">
                {{ item.name }}
              </div>
              <div v-for="(child, k) in item.children" :key="index + '-' + k" class="nav-popup-item"
                :class="{ active: judgePath(child) }" :style="{
                  height: item.expand ? '2.5rem' : '0',
                }" @click="changePath(child)">
                {{ child.name }}
              </div>
            </div>
            <div v-else class="nav-popup-item" :class="{ active: judgePath(item) }" @click="changePath(item)">
              {{ item.name }}
            </div>
          </template>
        </div>
      </div>
    </van-popup>
  </template>
</template>
<script setup lang="ts">
  const store = useStore();

  import weblogo2 from "@/assets/logo2.png";
  import weblogo1 from "@/assets/logo1.png";
  import { caseList } from "@/api/case";
  import { publicSrc } from "@/utils/common";

  const { proxy } = getCurrentInstance() as any;
  const router = useRouter();
  const route = useRoute();

  const menuList = ref < any > ([
    { name: "首页", path: "/pc/index" },
    { name: "产品服务", path: "/pc/product", children: [] },
    { name: "解决方案", path: "/pc/scheme", children: [] },
    { name: "项目案例", path: "/pc/case", children: [] },
    { name: "生态产品", path: "/pc/ecology", children: [] },
    { name: "关于我们", path: "/pc/about" },
    { name: "联系我们", path: "/pc/contact" },
  ]);
  const current = ref < string > ("/"); // 当前导航
  const currentIndex = ref < number > (0); // 当前导航索引
  const hoverIndex = ref < number > (-1); // 鼠标悬停索引
  const navChildren = ref < any > ([]); // 导航子菜单
  const mouseHover = ref < boolean > (false); // 鼠标是否悬停
  const scrollTop = ref < number > (0); // 滚动距离
  const contrastList = ref < any > ([
    // 需要改变背景色的导航
    "/m/product",
    "/m/about",
    "/m/news",
    "/m/about/hire",
    "/m/contact",
    "/m/ecology/detail",
    "/m/case",
    "/pc/product",
    "/pc/about",
    "/pc/news",
    "/pc/contact",
    "/pc/case",
    "/pc/ecology/detail", // 添加生态产品详情页路径
  ]);

  const isExpand = ref < boolean > (false); // 展开菜单

  // 根据滚动距离动态改变背景色
  const navStyle = computed(() => {
    // 检查当前路径是否包含 ecology/detail
    const isEcologyDetail = current.value?.includes('/ecology/detail');

    if (isEcologyDetail) {
      return {
        color: "#fff",
        background: "rgba(0, 0, 0, 0.2)",
        backdropFilter: "blur(4.86957px)",
      };
    }

    // const opacity = Math.min(scrollTop.value / 1000, 0.5); // 限制最大为 1
    const value = Math.min((scrollTop.value / 1000) * 10, 10); // 限制最大为 14
    return {
      color: navColor.value,
      // background: `rgba(0, 0, 0, ${opacity})`,
      backdropFilter: `blur(${value}px)`,
    };
  });

  // 导航logo
  const navLogo = computed(() => {
    let logo;
    if (mouseHover.value) {
      logo = weblogo1;
    } else if (contrastList.value.includes(current.value)) {
      logo = scrollTop.value > 200 ? weblogo2 : weblogo1;
    } else {
      logo = weblogo2;
    }
    return logo;
  });

  // 导航背景色
  const navColor = computed(() => {
    // 检查当前路径是否包含 ecology/detail
    const isEcologyDetail = current.value?.includes('/ecology/detail');

    if (isEcologyDetail) {
      return "#fff";
    }

    if (contrastList.value.includes(current.value)) {
      return scrollTop.value > 200 ? "#fff" : "#0f0e36";
    } else {
      return "#fff";
    }
  });

  // 导航图标样式
  const iconStyle = computed(() => {
    if (contrastList.value.includes(current.value)) {
      return {
        fontSize: "2.5rem",
        color: scrollTop.value > 200 ? "#fff" : "#5a9cf8",
      };
    } else {
      return {
        fontSize: "2.5rem",
        color: "#fff",
      };
    }
  });

  onMounted(() => {
    getList();
    getNavIndex();
    window.addEventListener("scroll", handleScroll);
  });

  onBeforeUnmount(() => {
    window.removeEventListener("scroll", handleScroll);
  });

  watch(
    () => router.currentRoute.value.path,
    () => {
      getNavIndex();
    }
  );

  // 判断当前路径是否匹配
  const judgePath = (item: any) => {
    if (item.query) {
      return (
        current.value === item.path &&
        JSON.stringify(item.query) === JSON.stringify(route.query)
      );
    }
    return item.path === current.value;
  };

  // 获取导航索引
  const getList = async () => {
    await getCaseList();
    await getProductList();
    await getSchemeList();
    // await getEcologyList();
    if (proxy.isMobile) {
      // 移动端则将所有/pc替换成/m
      menuList.value = menuList.value.map((item: any) => {
        if (item.path.indexOf("/pc") > -1) {
          item.path = item.path.replace("/pc", "/m");
        }
        if (item.children) {
          item.children = item.children.map((child: any) => {
            if (child.path.indexOf("/pc") > -1) {
              child.path = child.path.replace("/pc", "/m");
            }
            return child;
          });
        }
        return item;
      });
    }
  };

  // 获取产品服务列表
  const getProductList = () => {
    return new Promise((resolve) => {
      store.dispatch("setService").then((list: any) => {
        menuList.value[1].children = list;
        resolve(list);
      });
    });
  };

  // 获取项目案例列表
  const getCaseList = () => {
    return new Promise((resolve) => {
      caseList({ pageNum: 1, pageSize: 8 }).then((res: any) => {
        nextTick(() => {
          let list = res.rows;
          menuList.value[3].children = list.map((item: any) => {
            return {
              ...item,
              name: item.title,
              icon: publicSrc(item.icon),
              path: "/pc/case",
              desc: item.intro,
              query: {
                id: item.id,
              },
            };
          });
        });
        resolve(res.rows);
      });
    });
  };

  // 获取生态产品列表
  // const getEcologyList = () => {
  //   return new Promise((resolve) => {
  //     store.dispatch("setEcology").then((list: any) => {
  //       menuList.value[3].children = list;
  //       console.log(menuList.value[3], "navChildren---------------");
  //       resolve(list);
  //     });
  //   });
  // };
  // 获取解决方案列表
  const getSchemeList = () => {
    return new Promise((resolve) => {
      store.dispatch("setSolution").then((list: any) => {
        menuList.value[2].children = list;
        resolve(list);
      });
    });
  };

  // 获取当前导航索引
  const getNavIndex = () => {
    current.value = router.currentRoute.value.path;
    currentIndex.value = menuList.value.findIndex((i: any) => i.path === current.value);
    menuList.value.forEach((item: any) => {
      item.children &&
        item.children.forEach((child: any) => {
          if (child.path.includes(current.value)) item.expand = true;
        });
    });
  };

  // 监听滚动距离
  const handleScroll = () => {
    scrollTop.value = document.documentElement.scrollTop || document.body.scrollTop;
  };

  // 点击导航
  const changeNav = (item: any, index: number) => {
    if (item.children && item.children.length > 0) {
      mouseenter(item, index);
    } else {
      current.value = item.path;
      currentIndex.value = index;
      router.push({
        path: item.path,
        query: item.query || {},
      });
    }
  };

  // 切换子导航
  const changePath = (item: any) => {
    isExpand.value = false;
    current.value = item.path;
    currentIndex.value = hoverIndex.value;
    hoverIndex.value = -1;
    mouseleave();
    router.push({
      path: item.path,
      query: item.query || {},
    });
  };

  // 移动端展开子导航
  const handleExpandSubNav = (item: any) => {
    item.expand = !item.expand;
    if (item.expand) {
      menuList.value.forEach((i: any) => {
        i.children?.forEach((child: any) => {
          if (child.path != item.path) {
            i.expand = false;
          }
        });
      });
    }
  };

  // 移动端展开菜单
  const expandMenu = () => {
    isExpand.value = !isExpand.value;
    menuList.value.forEach((i: any) => {
      i.children?.forEach((child: any) => {
        if (child.path.includes(current.value)) {
          i.expand = true;
        } else {
          i.expand = false;
        }
      });
    });
  };

  // 鼠标移入
  const mouseenter = (item: any, index: number) => {

    navChildren.value = item.children || [];
    hoverIndex.value = index;
    mouseHover.value = item.children && item.children.length > 0;
  };

  // 鼠标移出
  const mouseleave = () => {
    navChildren.value = [];
    mouseHover.value = false;
  };
</script>
<style lang="scss" scoped>
  ::v-deep .el-cascader-node.in-active-path,
  .el-cascader-node.is-active,
  .el-cascader-node.is-selectable.in-checked-path {
    color: #000;
  }

  .nav-menu {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 9;

    .container {
      height: 112px;

      .nav-logo {
        width: 125px;
        height: 29px;
        transition: all 0.3s;
      }

      .nav-list {
        height: 100%;
        position: relative;

        .nav-item {
          width: 120px;
          height: 100%;
          text-align: center;
          font-size: 14px;
          transition: all 0.3s;

          &:hover {
            cursor: pointer;
            background-color: rgba(42, 129, 228, 0.1);
          }
        }
      }
    }
  }

  .tab-line {
    position: absolute;
    height: 3px;
    width: 55px;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    transition: all 0.3s;
  }

  .nav-children {
    position: absolute;
    top: 112px;
    width: 100%;
    height: auto;
    background-color: #fff;
    color: #000;
    box-shadow: 0 10px 10px rgba(54, 54, 54, 0.2);
    z-index: 9;

    .container {
      height: auto;

      .children-item {
        width: 100%;
        height: 110px;
        border-radius: 4px;
        transition: all 0.3s;
        padding: 17px 15px;
        box-sizing: border-box;

        &:hover {
          cursor: pointer;
          background: #ffffff;
          box-shadow: 0px 3px 10px rgba(0, 0, 0, 0.1);
        }

        .item-icon {
          height: 24px;
          width: 24px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 6px;
          }
        }

        .item-info {
          font-size: 14px;
          font-weight: 700;
          letter-spacing: 0px;
          line-height: 19.6px;
          color: #000000;
          margin: 10px 0;

          .item-hot {
            display: inline-block;
            width: 26px;
            height: 12px;
            font-size: 8px;
            border-radius: 3px;
            color: #c7000b;
            text-align: center;
            line-height: 12px;
            background: #f4e8e8;
            vertical-align: middle;
          }
        }

        .item-desc {
          font-size: 12px;
          letter-spacing: 0px;
          line-height: 16.8px;
          color: rgba(97, 97, 97, 1);
        }
      }
    }
  }

  .active {
    // color: #0484f8 !important;
    font-weight: 600 !important;
  }

  .mouseHover {
    background-color: #fff !important;

    .container {
      .nav-logo {
        mix-blend-mode: normal !important;
      }

      .nav-list {
        .nav-item {
          color: #0f0e36;
        }
      }
    }
  }

  /** 移动端 */
  .nav-menu-mobile {
    position: fixed;
    top: 0;
    z-index: 30;
    display: flex;
    height: 80px;
    width: 100%;
    padding: 1.25rem;
    box-sizing: border-box;
    align-items: center;
    justify-content: space-between;

    img {
      width: 8.5625rem;
    }
  }

  .nav-popup {
    width: 18.75rem;
    height: 100vh;

    .drawer-logo {
      width: 6.25rem;
      margin: 1.25rem;
    }

    &-list {
      padding: 0.25rem;
      box-sizing: border-box;

      .nav-popup-group {
        margin: 0.25rem;

        .nav-popup-label {
          color: #fff;
          font-size: 0.875rem;
          padding: 0.625rem;
          background-color: rgba(231, 242, 255, 0.4);
          transition: all 0.3s;

          &:active {
            background-color: rgba(231, 242, 255, 0.5);
          }
        }

        .nav-popup-item {
          padding-left: 1.25rem;
          margin: 0;
        }
      }

      .nav-popup-item {
        line-height: 2.5rem;
        font-size: 0.875rem;
        color: #fff;
        background-color: rgba(231, 242, 255, 0.2);
        margin: 0.25rem;
        transition: all 0.3s;
        padding-left: 0.625rem;
        overflow: hidden;

        &:active {
          color: #ddd;
          background-color: rgba(231, 242, 255, 0.4);
        }
      }
    }
  }
</style>
<style>
  .nav-van-popup {
    /* background: rgba(255, 255, 255, 0.4) !important; */
    background: rgba(255, 255, 255, 0) !important;
    backdrop-filter: blur(1.25rem) !important;
  }
</style>